package com.sgb.kjwl.view.ui.activity.home;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityZuLinSearchBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.CarBrandEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.view.ui.activity.ZulinSearchResultActivity;
import com.sgb.kjwl.view.ui.adapter.lease.CarSideBarAdapter;
import com.sgb.kjwl.view.ui.adapter.lease.LeaseSearchAdapter;
import com.sgb.kjwl.view.ui.adapter.lease.LeaseSearchTipAdapter;
import com.sgb.kjwl.viewmodel.home.ZuLinSearchModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick2;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ZuLinSearchActivity extends AppActivity {
    @Inject
    ZuLinSearchModel model;
    private ActivityZuLinSearchBinding binding;
    private InputMethodManager im;
    private TagAdapter historyAdapter;
    private TagAdapter hotAdapter;
    private LeaseSearchAdapter searchAdapter;
    private List<DictEntity3> tipList = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, ZuLinSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_zu_lin_search);
        binding.setViewModel(model);
        binding.ivBack.setOnClickListener(this);
        binding.tvSearch.setOnClickListener(this);
        binding.ivDelete.setOnClickListener(this);
        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        binding.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.editSearch.getText().toString())) {
                        MToast.showToast(ZuLinSearchActivity.this, "请输入关键字");
                        return true;
                    }
                }
                return false;
            }
        });
        binding.editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() > 0) {
                    model.getCatoryPrompt(s.toString().trim());
                }else{
                    binding.layoutTip.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void init() {
        //获取本地搜索记录
        model.getSearchHistoryListData();
        //获取服务的热词搜索
        model.getLeaseSearchAreaCode();

        initChangeText();
    }

    public void showTipList(List<DictEntity3> list) {
        this.tipList = list;
        if (tipList != null && tipList.size() > 0) {
            searchAdapter.setSelectedText(binding.editSearch.getText().toString().trim());
            searchAdapter.setDatas(tipList);
            if (binding.layoutTip.getVisibility() == View.GONE) {
                binding.layoutTip.setVisibility(View.VISIBLE);
            }
        } else {
            binding.layoutTip.setVisibility(View.GONE);
        }
    }


    private void initChangeText() {
        searchAdapter = new LeaseSearchAdapter(this, tipList);
        binding.rvTip.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.rvTip.setLayoutManager(new LinearLayoutManager(this));
        binding.rvTip.setAdapter(searchAdapter);
        searchAdapter.setOnItemClick(new AdapterOnItemClick2<DictEntity3>() {
            @Override
            public void onItemClick(DictEntity3 dictEntity3, int position) {
                binding.editSearch.setText(dictEntity3.getName());
                binding.tvSearch.callOnClick();
                binding.layoutTip.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                if (binding.editSearch.getText().toString().isEmpty()) {
                    goSearch("");
                } else {
                    goSearch(binding.editSearch.getText().toString().trim());
                    recordsLocal(binding.editSearch.getText().toString().trim());
                }
                break;
            case R.id.iv_delete:
                cleanHistoryWord();
                break;
        }
    }

    /**
     * //清除本地搜索记录
     */
    private void cleanHistoryWord() {
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.ZULIN_SEARCH_HISTORY, "");
        model.getSearchHistoryListData();
    }

    /**
     * 将搜索词汇记录在本地
     *
     * @param newWords
     */
    private void recordsLocal(String newWords) {
        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.ZULIN_SEARCH_HISTORY, "");
        StringBuffer oldWords = new StringBuffer();
        if (null != historyWords && !historyWords.isEmpty()) {
            String[] arr = historyWords.split(","); //字符串转数组,  用,分割
            for (int i = 0; i < arr.length; i++) {
                if (i < 10) {//最多只记录10条
                    if (newWords.equals(arr[i])) {
                        //剔除相同的字符
                    } else {
                        oldWords.append(arr[i] + ",");
                    }
                }
            }
        }
        String allHistoryWords = newWords + "," + oldWords;
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.ZULIN_SEARCH_HISTORY, allHistoryWords);
    }


    //设置热搜搜索词汇
    public void setHotHistoryData(List<String> ls) {
        if (ls == null || ls.size() == 0) return;
        binding.editSearch.setHint(ls.get(0));
        final LayoutInflater mInflater = LayoutInflater.from(ZuLinSearchActivity.this);
        hotAdapter = new TagAdapter<String>(ls) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_zulin_search_words, binding.searchHistoryList, false);
                TextView tv = layout.findViewById(R.id.name);
                tv.setText(s);
                return layout;
            }
        };
        binding.searchHotList.setAdapter(hotAdapter);
        binding.searchHotList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Log.v("search=", ls.get(position));
                goSearch(ls.get(position));
                recordsLocal(ls.get(position));
                return true;
            }
        });
    }


    /**
     * 设置历史搜索词汇
     *
     * @param ls
     */
    public void setSearchHistoryData(List<String> ls) {
        if (ls == null || ls.size() == 0) {
            binding.tvNoSearch.setVisibility(View.VISIBLE);
        } else {
            binding.tvNoSearch.setVisibility(View.GONE);
        }
        final LayoutInflater mInflater = LayoutInflater.from(ZuLinSearchActivity.this);
        historyAdapter = new TagAdapter<String>(ls) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_zulin_search_words, binding.searchHistoryList, false);
                TextView tv = layout.findViewById(R.id.name);
                tv.setText(s);
                return layout;
            }
        };
        binding.searchHistoryList.setAdapter(historyAdapter);
        binding.searchHistoryList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                goSearch(ls.get(position));
                recordsLocal(ls.get(position));
                return true;
            }
        });
    }


    private void goSearch(String words) {
        if(!TextUtils.isEmpty(words)){
            model.getCatoryPrompt(words);
        }
        jumpPage(words);
    }

    /**
     * 跳入租赁结果页面
     *
     * @param words
     */
    private void jumpPage(String words) {
        ZulinSearchResultActivity.start(getActivity(), words);//租赁结果页面searchable
    }
}
